﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.ComponentModel;

namespace GT
{
    public class StorageObject : DynamicObject, INotifyPropertyChanged
    {
        private Dictionary<string, object> otherValues = new Dictionary<string, object>();
        private object BaseObject;

        public StorageObject()
        {
            BaseObject = new object();
        }

        public StorageObject(object baseObject)
        {
            BaseObject = baseObject;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            try
            {
                result = BaseObject.GetPropertyValue(binder.Name, !binder.IgnoreCase);
                
                if (PropertyChanged != null)
                    PropertyChanged(BaseObject, new PropertyChangedEventArgs(binder.Name));
                return true;
            }
            catch
            {
                try
                {
                    otherValues[binder.Name] = Activator.CreateInstance(binder.ReturnType);
                    result = otherValues[binder.Name];
                    return true;
                }
                catch
                {
                    try
                    {
                        otherValues[binder.Name] = new object();
                        result = otherValues[binder.Name];
                        return true;
                    }
                    catch
                    {
                        return base.TryGetMember(binder, out result);
                    }
                }
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            try
            {
                BaseObject.SetPropertyValue(binder.Name, value, !binder.IgnoreCase);
                return true;
            }
            catch
            {
                try
                {
                    otherValues[binder.Name] = value;
                    return true;
                }
                catch
                {
                    return base.TrySetMember(binder, value);
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
